package leetcode.数组;

import java.util.Arrays;

public class 最接近的三数之和16 {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int close = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int temp = nums[left] + nums[right] + nums[i];
                if (Math.abs(temp - target) < Math.abs(close - target))
                    close = temp;
                if (temp < target) {
                    left++;
                } else if (temp > target) {
                    right--;
                } else {
                    return target;
                }

            }
        }
        return close;
    }

    public static void main(String[] args) {
        int[] nums = {-1,2,1,-4};
        int target = 1;
        int res = threeSumClosest(nums,target);
        System.out.println(res);
    }

}
